package com.eagle.roomsearch.util;

import com.alibaba.fastjson.JSON;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据类型转换工具类
 *
 * @author Jetvin
 * @version ╮(╯▽╰)╭
 * @date 2017年10月12日
 * @time 下午5:58:16
 */
public class CovertUtil {

    /**
     * Map转换成pojo实体
     *
     * @param map
     * @param object
     * @return
     * @author Jetvin
     * @date 2017年10月12日
     * @time 下午5:57:31
     * @version ╮(╯▽╰)╭
     */
    public static Object mapToPojo(Map<String, String> map, Object object) {

        return JSON.parseObject(JSON.toJSONString(map), object.getClass());
    }

    /**
     * pojo实体转换成Map
     *
     * @param object
     * @return
     * @author Jetvin
     * @date 2017年10月12日
     * @time 下午5:56:28
     * @version ╮(╯▽╰)╭
     */
    public static Map<String, String> pojoToMap(Object object) {

        @SuppressWarnings("unchecked")
        Map<String, String> map = JSON.parseObject(JSON.toJSONString(object), Map.class);

        return map;
    }

    /**
     * xml格式 转换为 Map格式
     *
     * @param xml
     * @return
     * @author Jetvin
     * @date 2017年9月25日
     * @time 下午11:30:30
     * @version
     */
    public static Map<String, String> xmlToMap(String xml) {
        Map<String, String> data = new HashMap<String, String>();
        try {

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }

            stream.close();

        } catch (Exception ex) {
            data = new HashMap<>();
            data.put("msg", "xml转map错误");
        }

        return data;
    }

    /**
     * Map格式 转换为 xml格式(不带CDATA)
     *
     * @param map
     * @return
     * @author Jetvin
     * @date 2017年9月25日
     * @time 下午11:35:42
     * @version ╮(╯▽╰)╭
     */
    public static String mapToXml(Map<String, String> map) {

        return mapToXml(map, false);
    }

    /**
     * Map格式 转换为 xml格式
     *
     * @param map
     * @param CDATA
     * @return
     * @author Jetvin
     * @date 2017年10月10日
     * @time 下午3:03:55
     * @version ╮(╯▽╰)╭
     */
    public static String mapToXml(Map<String, String> map, boolean CDATA) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            Element root = document.createElement("xml");
            document.appendChild(root);
            if (CDATA) {
                for (String key : map.keySet()) {
                    String value = map.get(key) + "";
                    value = value.trim();
                    Element filed = document.createElement(key);
                    CDATASection cdata = document.createCDATASection(value);
                    filed.appendChild(cdata);
                    root.appendChild(filed);
                }
            } else {
                for (String key : map.keySet()) {
                    String value = map.get(key) + "";
                    value = value.trim();
                    Element filed = document.createElement(key);
                    filed.appendChild(document.createTextNode(value));
                    root.appendChild(filed);
                }
            }
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
            StringBuilder xml = new StringBuilder();
            xml.append(writer.getBuffer());
            writer.close();

            return xml.toString();

        } catch (Exception e) {

            ExceptionUtil.printf(e);
            return "map转xml错误";
        }

    }

}
